package com.cloxtec.scada.utils;

import com.alibaba.fastjson.JSONObject;
import com.cloxtec.scada.service.MqttPubClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

@Component
@Slf4j
public class TimerTaskHelper {

    @Resource
    public LogHelper logHelper;

    @Resource
    private MongoHelper mongoHelper;

    @Resource
    private ParamHelper paramHelper;

    @Resource
    private MqttPubClient mqttPubClient;

    private Timer timer = new Timer();
    private Map<String, OnTimeTask> tasks = new HashMap<>();

    public void createTask(JSONObject task){
        OnTimeTask timerTask = new OnTimeTask(task);
        timer.schedule(timerTask, 5000, task.getInteger("task_interval") * 1000);
        tasks.put(task.getString("_id"), timerTask);
    }

    public void stopTask(String id){
        OnTimeTask task = tasks.get(id);
        if (task != null){
            task.cancel();
            //task = null;
            tasks.remove(id);
        }
    }

    public void StopAllTask(){
        timer.cancel();
        tasks.clear();
    }

    public void init() {
        startTimerTask();
    }

    public void startTimerTask() {
        List<JSONObject> lstObjs = mongoHelper.find("param_task");
        for (JSONObject task : lstObjs) {
            createTask(task);
        }
    }

    public void restartTimerTask(String id) {
        Map<String, Object> criteriaParams = new HashMap<String, Object>();
        criteriaParams.put("_id", id);
        List<JSONObject> lstObjs = mongoHelper.find("param_task", criteriaParams);
        JSONObject task = null;
        if (lstObjs.size() > 0) {
            task = lstObjs.get(0);
            stopTask(id);
            createTask(task);
        }
    }

    public void addTask(String id) {
        JSONObject task = paramHelper.getParamById("param_task", id);
        if (task != null) {
            createTask(task);
            mqttPubClient.broadcastOperationMsg("添加定时任务完成，任务已经启动....");
        }
    }

    public void delTask(String id) {
        stopTask(id);
        mqttPubClient.broadcastOperationMsg("删除定时任务：" + id + " 完成....");
    }

    public void updateTaskParam(String id) {
        JSONObject task = paramHelper.getParamById("param_task", id);
        if (task != null) {
            stopTask(id);
            createTask(task);
            mqttPubClient.broadcastOperationMsg("定时任务：" + id + " 已经更新参数并重新启动....");
        }
    }
}
